package com.fileshare.web.interceptor;

import com.fileshare.web.dto.info.LoginInfo;
import com.fileshare.web.entity.User;
import com.fileshare.web.service.WebPageService;
import com.fileshare.web.utils.IPKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

import static com.fileshare.web.constant.WebConst.LOGIN_INFO;
import static com.fileshare.web.constant.WebConst.USER_AGENT;

/**
 * 自定义拦截器
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseInterceptor.class);
    @Resource
    private WebPageService webPageService;

    @Override
    public boolean preHandle(HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object o) throws Exception {
        String uri = request.getRequestURI();
        LOGGER.info("UserAgent: {}", request.getHeader(USER_AGENT));
        LOGGER.info("用户访问地址: {}, 来路地址: {}", uri, IPKit.getIpAddrByRequest(request));
        handleLoginInfo(request);
        return true;
    }

    private void handleLoginInfo(HttpServletRequest request) {
        Object loginInfo = request.getSession().getAttribute(LOGIN_INFO);
        if (loginInfo instanceof LoginInfo) {
            LoginInfo info = (LoginInfo) loginInfo;
            request.setAttribute(LOGIN_INFO, info);
            User user = info.getUser();
            List<String> authorities = info.getAuthorities();
            List<GrantedAuthority> authorityList = authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, authorityList);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object o, ModelAndView modelAndView) {
        //一些工具类和公共方法
        request.setAttribute("pageService", webPageService);
    }

    @Override
    public void afterCompletion(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object o, Exception e) {

    }
}
